package servlet;

import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Participation;
import DAO.ParticipationDao;
import DAO.StudyDao;
import DAO.UserDao;

public class StudyApplyAction implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		HttpSession session=request.getSession();
		ActionForward forward=null;
		
		ParticipationDao participationDao = new ParticipationDao();
		StudyDao studyDao = new StudyDao();
		
		int studyId = request.getParameter("studyId") != null
				&& request.getParameter("studyId") != "" ? Integer
				.parseInt(request.getParameter("studyId")) : 0;
		int userId = session.getAttribute("userid") != null
				&& session.getAttribute("userid") != "" ? Integer
				.parseInt((String)session.getAttribute("userid")) : 0;
		if (userId < 1) {
			session.invalidate();
			Util.ShowError(response, "로그인해주세요");
		}
		if (studyId < 1) {
			Util.ShowError(response, "잘못 된 접근입니다");
		}
		
		if(studyDao.getStudyInfo(studyId).getCurrentMember()<studyDao.getStudyInfo(studyId).getMemberLimit()){
			
			ArrayList<Participation> participation = new ArrayList<Participation>();
			participation = participationDao.getSameStudyPotentialMember(studyId);
			for(int i=0; i<participation.size();i++)
			{
				if(userId==participation.get(i).getUid()){
					Util.ShowError(response, "이미 신청한 스터디입니다.");
					return forward;
				}
				
			}
			participation = participationDao.getSameStudyMember(studyId);
			for(int i=0; i<participation.size();i++)
			{
				if(userId==participation.get(i).getUid()){
					Util.ShowError(response, "이미 가입한 스터디입니다.");
					return forward;
				}
				
			}
			
			UserDao userDao = new UserDao();
			
			
			if(userDao.getUserInfo(userId).getPoint()>=studyDao.getStudyInfo(studyId).getDeposit()){
				participationDao.insertParticipation(studyId, Integer.parseInt((String) session.getAttribute("userid")));
			}
			else {
				Util.ShowError(response, "잔액이 부족합니다.");
				return forward;
			}
			
			
		}
		else {
			Util.ShowError(response, "스터디 방이 가득찼습니다.");
			return forward;
		}
		
		
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<script>");
		out.println("history.go(-1);");
		out.println("</script>");
		
		out.flush();
		out.close();
	
		
		return forward;
	}

}
